import { useUserInfo } from "@/features/business/HomePage_deprecated"
import { useAuth as useAuthV2 } from "@/features/useAuth"
import { useCountDown } from "@/features/useCountDown"
import { useLoginAction } from "@/features/useSearchAction"
import { CustomError } from "@/utils/error"
import { css } from "@emotion/react"
import { motion } from "motion/react"
import { useCallback, useEffect, useMemo } from "react"
import styled from "styled-components"
import { useUserWallet } from "@/features/business/HomePage_deprecated/atoms_deprecated"
import AgreeHint from "./components/AgreeHint"
import OtpCodeInputFormItem from "./components/OtpCodeInputFormItem"
import PhoneInputFormItem from "./components/PhoneInputFormItem"
import SubmitButton from "./components/SubmitButtons"
import { LoginOtpCodeForm, LoginOtpForm } from "./data"
import { LoginLayout } from "./layouts"
import Svg from "@/components/base/Svg"
const Block = styled.div`
    display: flex;
    flex-direction: column;
    gap: 8rem;
    margin-top: 0rem;
`

function LoginOtpPage() {
    const { payload, moveToStep, close } = useLoginAction()
    const form = LoginOtpForm.useForm({
        mode: "onSubmit",
        defaultValues: {
            countryCode: payload.data?.countryCode ?? "+63",
            number: payload.data?.number ?? "",
            agreeTerms: false,
        },
    })

    const { sendVerifyCode: sendOTP } = useAuthV2()

    return (
        <LoginLayout
            css={css`
                border-radius: 8rem 8rem 0 0;
                position: relative;
            `}
        >
            {/* 右上角关闭按钮 */}
            <Svg
                src={"login_page_v2/close.svg"}
                css={css`
                    position: absolute;
                    top: 16rem;
                    right: 16rem;
                    width: 16rem;
                    height: 16rem;
                `}
                onClick={close}
            />

            <Block
                css={css`
                    margin-top: 16rem;
                `}
            />
            <h3
                css={css`
                    padding: 0;
                    margin: 0;
                    font-family: Gilroy;
                    font-weight: 400;
                    font-size: 14rem;
                    line-height: 20rem;
                    letter-spacing: 0%;
                    text-align: center;
                    color: #cc0033;
                `}
            >
                Welcome to filbet
            </h3>
            <Block
                css={css`
                    margin-top: 16rem;
                `}
            />
            <h1
                css={css`
                    padding: 0;
                    margin: 0;
                    font-family: Gilroy;
                    font-weight: 700;
                    font-size: 22rem;
                    line-height: 36rem;
                    text-transform: capitalize;
                `}
            >
                Login With Code
            </h1>
            <Block
                css={css`
                    margin-top: 40rem;
                `}
            />
            <LoginOtpForm.FormProvider {...form}>
                <PhoneInputFormItem />
                <Block
                    css={css`
                        margin-top: 24rem;
                    `}
                />
                <SubmitButton
                    onSubmit={async (data) => {
                        if (!data.agreeTerms) {
                            form.setError("agreeTerms", {
                                message: "You must agree to the terms and conditions",
                            })
                            return
                        }

                        try {
                            const res = await sendOTP(
                                data.number.replace(/\s/g, ""),
                                data.countryCode,
                            )
                            if (res.success && res.data) {
                                moveToStep("login-otp-2", {
                                    otpId: res.data.id,
                                    countryCode: data.countryCode,
                                    number: data.number,
                                })
                            }
                            throw res.error
                        } catch (error) {
                            if (error instanceof CustomError) {
                                form.setError("number", { message: error.message })
                            } else {
                                form.setError("number", { message: "Failed to send OTP" })
                            }
                        }
                    }}
                >
                    Register / Login
                </SubmitButton>
                <Block
                    css={css`
                        margin-top: 12rem;
                    `}
                />
                <AgreeHint formUrl={"homeLogin"} />
                <button
                    css={css`
                        border: none;
                        background: none;
                        font-family: Gilroy;
                        font-weight: 400;
                        font-size: 16rem;
                        line-height: 24rem;
                        letter-spacing: 0%;
                        text-align: center;
                        color: #005ae0;
                        cursor: pointer;
                        align-self: center;
                    `}
                    onClick={() => {
                        moveToStep("login-password", {
                            countryCode: form.watch("countryCode"),
                            number: form.watch("number"),
                        })
                    }}
                >
                    Login With Password
                </button>
            </LoginOtpForm.FormProvider>
        </LoginLayout>
    )
}

export default LoginOtpPage

export function LoginOtpCodePage() {
    const { getUserInfo } = useUserInfo()
    const { getUserWallet } = useUserWallet()
    const { loginSuccess } = useLoginAction()

    const {
        count: countDownSeconds,
        isEnd: isCountDownEnd,
        reset: resetCountDown,
    } = useCountDown(30)
    const { sendVerifyCode: sendOTP } = useAuthV2()
    const { payload, moveToStep, setPayload } = useLoginAction()
    const form = LoginOtpCodeForm.useForm({
        mode: "onSubmit",
        defaultValues: {
            otpId: payload.data?.otpId ?? "",
            code: "",
        },
    })

    const { loginWithOtp: loginWithOTP } = useAuthV2()

    const handleLoginSuccess = useCallback(async () => {
        await getUserInfo()
        await getUserWallet()
        loginSuccess()
    }, [getUserInfo, getUserWallet, loginSuccess])

    const submit = useMemo(() => {
        return form.handleSubmit(async (data) => {
            if (form.formState.submitCount > 5) {
                form.setError("code", { message: "Too many attempts" })
                return
            }
            try {
                const result = await loginWithOTP(data.otpId, data.code)
                if (result.success) {
                    return handleLoginSuccess()
                }
                throw result.error
            } catch (error) {
                form.setValue("code", "")
                if (error instanceof CustomError) {
                    form.setError("code", { message: error.message })
                } else {
                    form.setError("code", { message: "Invalid code" })
                }
            }
        })
    }, [form, loginWithOTP, handleLoginSuccess])

    useEffect(() => {
        if (form.formState.isValid && !form.formState.isSubmitting) {
            submit()
        }
    }, [form.formState.isValid, form.formState.isSubmitting, submit])

    return (
        <LoginLayout
            css={css`
                border-radius: 8rem 8rem 0 0;
                position: relative;
            `}
        >
            {/* 右上角关闭按钮 */}
            <Svg
                src={"login_page_v2/close.svg"}
                css={css`
                    position: absolute;
                    top: 16rem;
                    right: 16rem;
                    width: 16rem;
                    height: 16rem;
                `}
                onClick={() =>
                    moveToStep("login-otp-1", {
                        countryCode: payload.data?.countryCode ?? "",
                        number: payload.data?.number ?? "",
                    })
                }
            />

            <Block
                css={css`
                    margin-top: 16rem;
                `}
            />
            <h3
                css={css`
                    padding: 0;
                    margin: 0;
                    font-family: Gilroy;
                    font-weight: 400;
                    font-size: 14rem;
                    line-height: 20rem;
                    letter-spacing: 0%;
                    text-align: center;
                    color: #cc0033;
                `}
            >
                Welcome to filbet
            </h3>
            <Block
                css={css`
                    margin-top: 16rem;
                `}
            />
            <h1
                css={css`
                    padding: 0;
                    margin: 0;
                    font-family: Gilroy;
                    font-weight: 700;
                    font-size: 22rem;
                    line-height: 36rem;
                    text-transform: capitalize;
                `}
            >
                Enter the code
            </h1>
            <h3
                css={css`
                    font-weight: 400;
                    font-family: Gilroy;
                    font-size: 14rem;
                    line-height: 20rem;
                    letter-spacing: 0%;
                    align-self: flex-start;
                    margin-bottom: 0;
                `}
            >
                We'll send a verification code to your mobile:
            </h3>
            <caption
                css={css`
                    font-weight: 500;
                    font-family: Gilroy;
                    font-size: 14rem;
                    line-height: 20rem;
                    letter-spacing: 0%;
                    align-self: flex-start;
                `}
            >
                {payload.data?.countryCode} {payload.data?.number}
            </caption>
            <LoginOtpCodeForm.FormProvider {...form}>
                <Block
                    css={css`
                        margin-top: 32rem;
                    `}
                />
                <OtpCodeInputFormItem />
                <div
                    css={css`
                        display: flex;
                        flex-direction: row;
                        gap: 8rem;
                        justify-content: space-between;
                        font-weight: 400;
                        font-family: Gilroy;
                        font-size: 14rem;
                        line-height: 16rem;
                        letter-spacing: 0%;
                    `}
                >
                    <div
                        css={css`
                            font-weight: 400;
                            color: #cc0033;
                            cursor: pointer;
                        `}
                        onClick={() => {
                            moveToStep("login-otp-1", {
                                countryCode: payload.data?.countryCode ?? "",
                                number: payload.data?.number ?? "",
                            })
                        }}
                    >
                        Reset phone number
                    </div>
                    <motion.div
                        onClick={async () => {
                            form.setValue("code", "")
                            const countryCode = payload.data?.countryCode ?? ""
                            const number = (payload.data?.number ?? "").replace(/\s/g, "")
                            try {
                                const res = await sendOTP(number, countryCode)
                                if (res.success && res.data) {
                                    setPayload({
                                        otpId: res.data.id,
                                        countryCode: payload.data?.countryCode ?? "",
                                        number: payload.data?.number,
                                    })
                                    resetCountDown()
                                    form.setError("code", { message: `otp code sent.` })
                                    return
                                }
                                throw res.error
                            } catch (error) {
                                if (error instanceof CustomError) {
                                    form.setError("code", { message: error.message })
                                } else {
                                    form.setError("code", { message: "Failed to login" })
                                }
                            }
                        }}
                        css={css`
                            font-weight: 400;
                            pointer-events: ${isCountDownEnd ? "auto" : "none"};
                            cursor: ${isCountDownEnd ? "pointer" : "default"};
                        `}
                        animate={{
                            color: isCountDownEnd ? "#cc0033" : "#000000",
                        }}
                    >
                        {!isCountDownEnd ? `Resend Code ${countDownSeconds}s` : "Resend Code"}
                    </motion.div>
                </div>
            </LoginOtpCodeForm.FormProvider>
        </LoginLayout>
    )
}
